package calvin.study.redis.demo1;

import java.util.concurrent.atomic.AtomicInteger;

import cn.hutool.db.nosql.redis.RedisDS;
import redis.clients.jedis.Jedis;

/**
 * 发布者（单点）
 */
public class RedisProducer implements Runnable {

	public static final String CHANNEL_KEY = "channel:1";
	//private volatile int count;
	
	private AtomicInteger count = new AtomicInteger(0);

	public void putMessage(String message) {
		Jedis jedis = RedisDS.create().getJedis();
		Long publish = jedis.publish(CHANNEL_KEY, message);// 返回订阅者数量
		System.out.println(
				Thread.currentThread().getName() + " put message,count=" + count + ",subscriberNum=" + publish);
		
		count.incrementAndGet();
	}

	@Override
	public void run() {
		for (int i = 0; i < 5; i++) {
			putMessage("消息：" + count);
		}
	}

	public static void main(String[] args) {
		RedisProducer messageProducer = new RedisProducer();
		Thread t1 = new Thread(messageProducer, "thread1");
		Thread t2 = new Thread(messageProducer, "thread2");
		Thread t3 = new Thread(messageProducer, "thread3");
		Thread t4 = new Thread(messageProducer, "thread4");
		Thread t5 = new Thread(messageProducer, "thread5");
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	}

}
